package com.aliyun.alink.devicesdk.demo;

import com.jcraft.jsch.*;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Vector;

public class SSHShell {
    private String host;

    private String username;

    private String password;

    private int port;

    private Vector<String> stdout;

    public SSHShell(final String ipAddress, final String username, final String password, final int port) {
        this.host = ipAddress;
        this.username = username;
        this.password = password;
        this.port = port;
        this.stdout = new Vector<String>();
    }

    public int execute(final String command) {

        System.out.println("ssh command: " + command);

        int returnCode = 0;
        JSch jsch = new JSch();
        SSHUserInfo userInfo = new SSHUserInfo();

        try {
            Session session = jsch.getSession(username, host, port);
            session.setPassword(password);
            session.setUserInfo(userInfo);
            session.connect();

            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);

            channel.setInputStream(null);
            BufferedReader input = new BufferedReader(new InputStreamReader(channel.getInputStream()));

            channel.connect();

            String line = null;
            while ((line = input.readLine()) != null) {
                stdout.add(line);
            }
            input.close();

            if (channel.isClosed()) {
                returnCode = channel.getExitStatus();
            }

            channel.disconnect();
            session.disconnect();
        } catch (JSchException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return returnCode;
    }

    public Vector<String> getStdout() {
        return stdout;
    }
}
